package com.finance.scheduler.job;

import com.finance.base.enums.PullStatusEnum;
import com.finance.framework.qurtz.TaskDescriptor;
import com.finance.scheduler.service.AbstractTask;
import com.finance.scheduler.service.LogisticsDataPuller;
import com.finance.system.bean.pojo.RecomputeTask;
import com.finance.system.bean.pojo.User;
import com.finance.system.service.IRecomputeTaskService;
import com.finance.util.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 重拉定时任务
 * Created by CBWL on 2017/5/22.
 */
@Component
@DisallowConcurrentExecution
public class RePullDataJob implements AbstractTask{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IRecomputeTaskService recomputeTaskService;

    @Autowired
    private LogisticsDataPuller pullDataManager;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        List<RecomputeTask> allUndo = this.recomputeTaskService.getAllUnPull();
        this.logger.info("运单重拉 未处理任务：{}",String.valueOf(allUndo));
        if(!CollectionUtils.isEmpty(allUndo)){
            for (RecomputeTask recomputeTask : allUndo) {
                Date month = null;
                 try {
                    month = DateUtil.str2date(recomputeTask.getMonth(),DateUtil.YEAR_AND_MONTH_FORMAT);
                     if(PullStatusEnum.UNDO.getState() == recomputeTask.getPullStatus()){
                         recomputeTask.setPullStatus(PullStatusEnum.PULLING.getState());
                         User user = new User();
                         user.setId(0L);
                         this.recomputeTaskService.updateRecomputeTask(recomputeTask,user);
                     }
                     this.logger.info("重拉开始：{}的运单数据 时间：{}", month, DateUtil.dateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"));
                     this.pullDataManager.pullData(recomputeTask);
                     this.logger.info("重拉结束：{}的运单数据 时间：{}", month, DateUtil.dateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"));
                 } catch (Throwable e) {
                     logger.error(e.getMessage(),e);
                 }
            }
        }
    }

    @Override
    public TaskDescriptor descriptor() {
        return new TaskDescriptor("按指定月份重拉","pullData","RePullDataJobTrg","pullData","0 */2 * ? * *",this.getClass().getCanonicalName(),"重新拉取运单数据");
    }

}
